package org.example.controller;

import org.example.pojo.Doctor.Doctor;
import org.example.pojo.Doctor.OutpatientClinic;
import org.example.pojo.Doctor.Schedule;
import org.example.pojo.DoctorUser;
import org.example.pojo.Patient.PatientUser;
import org.example.pojo.User;
import org.example.service.AdminUserService;
import org.example.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.example.service.HospitalService;
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private HospitalService hospitalService;
    //获取所有患者信息
    @GetMapping("/patients")
    public Result getAllPatients() {
        List<PatientUser> patients = adminUserService.getAllPatients();
        return Result.success(patients);
    }
    //获取所有医生信息
    @GetMapping("/doctors")
    public Result getAllDoctors() {
        List<DoctorUser> doctors = adminUserService.getAllDoctors();
        return Result.success(doctors);
    }
    //根据id获取患者信息
    @GetMapping("/getPatient")
    public Result getPatientById(Integer id) {
        PatientUser patient = adminUserService.getPatientById(id);
        return Result.success(patient);
    }
    //根据id获取医生信息
    @GetMapping("/getDoctor")
    public Result getDoctorById(Integer doctorId) {
        Doctor doctor = adminUserService.getDoctorById(doctorId);
        return Result.success(doctor);
    }
    //更新患者信息
    @PutMapping("/updatePatient")
    public Result updatePatient(@RequestBody @Validated PatientUser patient) {
        System.out.println(patient);
        adminUserService.updatePatient(patient);
        return Result.success();
    }
    //更新医生信息
    @PutMapping("/updateDoctor")
    public Result updateDoctor(@RequestBody @Validated DoctorUser doctor) {
        adminUserService.updateDoctor(doctor);
        return Result.success();
    }
    //删除患者信息
    @DeleteMapping("/deletePatient")
    public Result deletePatient(Integer id) {
        adminUserService.deletePatient(id);
        return Result.success();
    }
    //删除医生信息
    @DeleteMapping("/deleteDoctor")
    public Result deleteDoctor(Integer id) {
        adminUserService.deleteDoctor(id);
        return Result.success();
    }
    //获取医生排班表(通过时间与科室Id查询)
    @GetMapping("/doctorSchedule")
    public Result getDoctorSchedule(@RequestParam(required = false) String scheduleDate, @RequestParam(required = false) Integer clinicId) {
        if (clinicId == null&&scheduleDate==null) {
            List<Schedule> doctorSchedule = adminUserService.getDoctorScheduleNull();
            return Result.success(doctorSchedule);
        }else if (clinicId == null) {
            List<Schedule> doctorSchedule = adminUserService.getDoctorScheduleByDate(scheduleDate);
            return Result.success(doctorSchedule);
        }else if (scheduleDate == null) {
            List<Schedule> doctorSchedule = adminUserService.getDoctorScheduleById(clinicId);
            return Result.success(doctorSchedule);
        }
        else {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                java.util.Date utilDate = formatter.parse(scheduleDate);
                java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                List<Schedule> doctorSchedule = adminUserService.getDoctorSchedule(sqlDate, clinicId);
                return Result.success(doctorSchedule);
            } catch (ParseException e) {
                // 替换为日志记录
                Logger logger = LoggerFactory.getLogger(AdminController.class);
                logger.error("日期解析失败", e);
                return Result.error("日期解析失败");
            }
        }
    }
    //增加医生排班表信息
    @PostMapping("/addDoctorSchedule")
    public Result addDoctorSchedule(@RequestBody Schedule schedule) {
        String dateString = schedule.getScheduleDate().toString(); // 示例日期
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            java.util.Date utilDate = formatter.parse(dateString);
            java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
            System.out.println(sqlDate);
            schedule.setScheduleDate(sqlDate);
        } catch (ParseException e) {
            // 替换为日志记录
            Logger logger = LoggerFactory.getLogger(AdminController.class);
            logger.error("日期解析失败", e);
            return Result.error("日期解析失败");
        }
        // 将字符串转换为LocalDate
        LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
        // 使用DayOfWeek枚举获取星期几
        int dayOfWeek = localDate.getDayOfWeek().getValue(); // getValue()返回1-7（1是Monday，7是Sunday）
        System.out.println("星期几（1-7）: " + dayOfWeek);
        schedule.setDayWeek(dayOfWeek);
        //通过医生id获取医生姓名
        String doctorName = adminUserService.getDoctorById(schedule.getDoctorId()).getName();
        schedule.setDoctorName(doctorName);
        Integer clinicId = adminUserService.getDoctorById(schedule.getDoctorId()).getClinicId();
        schedule.setClinicId(clinicId);
        //通过科室id获取科室名称
        List<OutpatientClinic> clinics = hospitalService.getAllClinics();
        clinics.forEach(clinic -> {
            if (clinic.getClinicId().equals(clinicId)) {
                schedule.setClinicName(clinic.getClinicName());
            }
        });
        adminUserService.addDoctorSchedule(schedule);
        return Result.success();
    }
    //删除医生排班表信息
    @DeleteMapping("/deleteDoctorSchedule")
    public Result deleteDoctorSchedule(Integer scheduleId) {
        adminUserService.deleteDoctorSchedule(scheduleId);
        return Result.success();
    }
    //更新医生排班表信息
    @PutMapping("/updateDoctorSchedule")
    public Result updateDoctorSchedule(@RequestBody Schedule schedule) {
        String dateString = schedule.getScheduleDate().toString(); // 示例日期
        System.out.println(schedule);
        // 将字符串转换为LocalDate
        LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
        // 使用DayOfWeek枚举获取星期几
        int dayOfWeek = localDate.getDayOfWeek().getValue(); // getValue()返回1-7（1是Monday，7是Sunday）
        //System.out.println("星期几（1-7）: " + dayOfWeek);
        schedule.setDayWeek(dayOfWeek);
        //通过医生id获取医生姓名
        String doctorName = adminUserService.getDoctorById(schedule.getDoctorId()).getName();
        schedule.setDoctorName(doctorName);
        Integer clinicId = adminUserService.getDoctorById(schedule.getDoctorId()).getClinicId();
        schedule.setClinicId(clinicId);
        //通过科室id获取科室名称
        List<OutpatientClinic> clinics = hospitalService.getAllClinics();
        clinics.forEach(clinic -> {
            if (clinic.getClinicId().equals(clinicId)) {
                schedule.setClinicName(clinic.getClinicName());
            }
        });
        adminUserService.updateDoctorSchedule(schedule);
        return Result.success();
    }

}
